package utils

import (
	"bufio"
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"log"
	"os"
	"strings"
)

// GetUuid 生成uuid
func GetUuid() string {
	u := uuid.New()
	return u.String()
}

// GetExtension 文件后缀名
func GetExtension(fileName string) string {
	index := strings.LastIndex(fileName, ".")
	if index == -1 {
		return ""
	}
	return fileName[index+1:]
}
func RspJsonMarshal(com interface{}, to interface{}) (err error) {

	marshal, err := json.Marshal(to)
	if err != nil {
		return err
	}
	err = json.Unmarshal(marshal, &com)
	if err != nil {
		return err
	}
	fmt.Println(com)
	return nil
}

func SaveFile(path string, data []byte) bool {
	// data, err := json.Marshal(t)
	// if err != nil {
	// 	fmt.Println("序列化错误")
	// 	return false
	// }

	s := string(data)
	file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Printf("错误%v\n", err)
		return false
	}
	defer file.Close()

	wiriter := bufio.NewWriter(file)
	wiriter.WriteString(s)
	wiriter.Flush()
	return true
}

func ReadFile(path string) []byte {
	data, err := os.ReadFile(path)
	if err != nil {
		fmt.Printf("读取文件错误%v", err)
	}
	if err != nil {
		fmt.Printf("序列化失败%v", err)
		return nil
	}
	return data
}
func DellFile(path string) bool {
	err := os.Remove(path)
	if err != nil {
		return false
	} else {
		return true
	}
}

// DeleteFilesWithSuffix 删除文件夹 指定后缀名字
func DeleteFilesWithSuffix(dir string, suffix string) {
	files, err := os.ReadDir(dir) // 读取目录内容
	if err != nil {
		log.Fatalf("无法读取目录 %s: %v", dir, err)
	}

	for _, fileInfo := range files {
		fileName := fileInfo.Name()
		filePath := fmt.Sprintf("%s/%s", dir, fileName)

		// 判断文件名是否包含指定后缀
		if strings.HasSuffix(fileName, suffix) {
			err = os.Remove(filePath) // 删除文件
			if err != nil {
				log.Printf("无法删除文件 %s: %v", filePath, err)
			} else {
				fmt.Println("成功删除文件: ", filePath)
			}
		}
	}
}

func FilterEmptyStrings(slice []string) []string {
	var result []string
	for _, s := range slice {
		if s != "" {
			result = append(result, s)
		}
	}
	return result
}
